/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xui_lib.tabbar;

import ohos.agp.components.AttrHelper;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.PageSlider;
import ohos.agp.components.StackLayout;
import ohos.agp.components.TableLayout;
import ohos.app.Context;

import com.xuexiang.xui_lib.tabbar.tablayout.jptabbar.DensityUtils;
import com.xuexiang.xui_lib.util.AttrValue;
import com.xuexiang.xui_lib.util.Log;

import java.util.Arrays;

/**
 * 主要的底部导航操作类,控制导航的行为
 *
 * @since 2021-04-21
 */
public class JPTabBar extends DirectionalLayout {
    // 默认的图标大小
    private static final int DEFAULT_ICONSIZE = 25;

    // 字体默认大小
    private static final int DEFAULT_TEXTSIZE = 10;

    // 默认的没有选中的文字和图标的颜色
    private static final int DEFAULT_NORMAL_COLOR = 0xFFC2B7B8;

    // 默认的上下背景间隔
    private static final int DEFAULT_MARGIN = 3;
    private static final int DEFAULT_INDEX = 2;

    // 默认的选中颜色
    private static final int DEFAULT_SELECT_COLOR = 0xFFFF9915;

    // 默认中间图标底部距离
    private static final int DEFAULT_MIDDLEICONBOTTOM = 20;

    // 默认中间的左右间距
    private static final int DEFAULT_MIDDLEMARGIN = 40;
    private static final String TAG = "JPTabBar";
    private Context mContext;

    // 选中的当前Tab的位置
    private int mSelectIndex;

    // 中间按钮
    private Component mMiddleItem;
    private String[] mtitle;

    // 所有Tabitem
    private JPTabItem[] mJPTabItem;
    private int tabmiddleView;
    private int normalColor;
    private int selectColor;
    private int margin;
    private int marginTop;
    private int textSize;
    private int iconSize;
    private int centerWidth;
    private PageSlider mPageSlider;
    private MiddleItemClickedListener mMiddleItemClickedListener;
    private OnClickBarListener mOnClickBarListener;

    /**
     * 上下文类
     *
     * @param context
     * @param attrSet
     */
    public JPTabBar(Context context, AttrSet attrSet) {
        super(context, attrSet);
        initAttr(attrSet);
    }

    /**
     * 获取所有节点属性
     *
     * @param attrSet xml节点集合
     */
    private void initAttr(AttrSet attrSet) {
        setOrientation(HORIZONTAL);
        normalColor = AttrValue.get(attrSet, "TabNormalColor", DEFAULT_NORMAL_COLOR);
        selectColor = AttrValue.get(attrSet, "TabSelectColor", DEFAULT_SELECT_COLOR);
        textSize = AttrValue.getDimension(attrSet, "TabTextSize", AttrHelper.fp2px(DEFAULT_TEXTSIZE, getContext()));
        iconSize = AttrValue.getDimension(attrSet, "TabIconSize", AttrHelper.fp2px(DEFAULT_ICONSIZE, getContext()));
        margin = AttrValue.getDimension(attrSet, "TabMargin", AttrHelper.fp2px(DEFAULT_MARGIN, getContext()));
        marginTop = AttrValue.getDimension(attrSet, "TabMargin", AttrHelper.fp2px(DEFAULT_MARGIN, getContext()));
        centerWidth = AttrValue.getDimension(attrSet, "TabMiddleHMargin",
            AttrHelper.fp2px(DEFAULT_MIDDLEMARGIN, getContext()));
    }

    /**
     * 设置中间图标
     *
     * @param tabmiddleViews 中间图标
     */
    public void createMiddleView(int tabmiddleViews) {
        this.tabmiddleView = tabmiddleViews;
        if (tabmiddleView == 0) {
            return;
        }
        mMiddleItem = LayoutScatter.getInstance(getContext()).parse(tabmiddleView,
            (ComponentContainer) getComponentParent(), false);

        // 给中间自定义View填充额外参数,令布局在父View的中间和最下边的位置(父View指的是TabBar的父控件)
        mMiddleItem.setClickedListener(component -> {
            if (mMiddleItemClickedListener != null) {
                mMiddleItemClickedListener.onClick();
            }
        });
        fillMiddleParams();
    }

    public void setMiddleItemClickedListener(MiddleItemClickedListener listeners) {
        this.mMiddleItemClickedListener = listeners;
    }

    /**
     * 数据集合
     *
     * @param titles 文本数组
     * @param icon 图标数组
     * @param iconselect 选中的图标
     * @param tabmiddleViews 中间的图标
     */

    public void setDatas(String[] titles, int[] icon, int[] iconselect, int tabmiddleViews) {
        mtitle = Arrays.copyOf(titles,titles.length);
        removeAllComponents();
        setOrientation(HORIZONTAL);
        mJPTabItem = new JPTabItem[mtitle.length];
        for (int index = 0; index < mtitle.length; index++) {
            JPTabItem tabItem = new JPTabItem.Builder(getContext()).setTitle(mtitle[index])
                .setNormalIcon(icon[index]).setMargin(margin).setIndex(index).setSelectIcon(iconselect[index])
                .setNormalColor(normalColor).setRed(index == DEFAULT_INDEX).setSelectedColor(selectColor)
                .setIsSeleted(index == 0).setTextSize(textSize).setIconSize(iconSize).setMarginTop(marginTop)
                .setmiddleView(tabmiddleViews).build();
            mJPTabItem[index] = tabItem;
            tabItem.setClickedListener(component -> {
                tabItem.setBarSelected(true);
                if (mPageSlider != null) {
                    mPageSlider.setCurrentPage(tabItem.getIndex());
                }
                for (int leng = 0; leng < mJPTabItem.length; leng++) {
                    if (tabItem.getIndex() != leng) {
                        mJPTabItem[leng].setBarSelected(false);
                    }
                }
            });

            LayoutConfig config = new LayoutConfig(ComponentContainer.LayoutConfig.MATCH_CONTENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT);
            config.weight = 1;
            tabItem.setLayoutConfig(config);
            addComponent(tabItem);

            // 判断是不是准备到中间的tab,假如设置了中间图标就添加进去
            if (index == mJPTabItem.length / DEFAULT_INDEX - 1 && this.tabmiddleView != 0) {
                // 添加中间的占位距离控件
                Component stementview = new Component(mContext);
                LayoutConfig config1 = new LayoutConfig(
                    centerWidth, ComponentContainer.LayoutConfig.MATCH_CONTENT);
                addComponent(stementview, config1);
            }
        }
    }

    /**
     * MiddleItemClickedListener
     *
     * @since 2021-04-21
     */
    public interface MiddleItemClickedListener {
        /**
         * onClick
         */
        void onClick();
    }

    private void fillMiddleParams() {
        if (getComponentParent().getClass().equals(DependentLayout.class)) {
            DependentLayout.LayoutConfig config = (DependentLayout.LayoutConfig) mMiddleItem.getLayoutConfig();
            config.setMargins(0, 0, 0, DensityUtils.vp2px(getContext(), DEFAULT_MIDDLEICONBOTTOM));
            config.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_BOTTOM);
            config.addRule(DependentLayout.LayoutConfig.HORIZONTAL_CENTER);
            mMiddleItem.setLayoutConfig(config);
        } else if (getPadding().getClass().equals(StackLayout.class)) {
            StackLayout.LayoutConfig config = (StackLayout.LayoutConfig) mMiddleItem.getLayoutConfig();
            config.setMargins(0, 0, 0, DensityUtils.vp2px(getContext(), DEFAULT_MIDDLEICONBOTTOM));
            config.alignment = TableLayout.Alignment.ALIGNMENT_BOTTOM;
            mMiddleItem.setLayoutConfig(config);
        }
        ((ComponentContainer) getComponentParent()).addComponent(mMiddleItem);
    }

    /**
     * PageSlider滑动状态
     *
     * @param pager
     */
    public void setPageSlider(PageSlider pager) {
        mPageSlider = pager;
        pager.addPageChangedListener(new PageSlider.PageChangedListener() {
            public void onPageSliding(int itemPos, float itemPosOffset, int itemPosPixles) {
            }

            @Override
            public void onPageSlideStateChanged(int state) {
            }

            @Override
            public void onPageChosen(int itemPos) {
                if (itemPos == mSelectIndex) {
                    return;
                }
                Log.e(TAG, "onPageChosen itemPos %d", itemPos);

                mJPTabItem[itemPos].setBarSelected(true);
                mJPTabItem[mSelectIndex].setBarSelected(false);
                mSelectIndex = itemPos;

                if (mOnClickBarListener != null) {
                    mOnClickBarListener.onClick(mtitle[itemPos]);
                }
            }
        });
    }

    public void setOnClickPageListener(JPTabBar.OnClickBarListener listener) {
        this.mOnClickBarListener = listener;
    }

    /**
     * OnClickBarListener
     *
     * @since 2021-04-21
     */
    public interface OnClickBarListener {
        /**
         * onClick
         *
         * @param name tab标题
         */
        void onClick(String name);
    }
}
